<script setup>
import { ref, reactive, watch } from "vue";
import { onReachBottom, onShow } from "@dcloudio/uni-app";
import { request } from "@/common/http";
import { ApiUrl } from "@/common/ApiUrl";
import { Toast, jumpPage } from "@/utils";
import NavBar from "../../components/NavBar.vue";

const state = reactive({
	params: {
		/* 用户手机号码 */
		mobile: null,
		/* 用户密码 */
		password: null,
		/* 用户角色ID */
		roleId: null,
		/* 用户名称 */
		userName: "",
	},
	/* 角色名称 */
	roleText: "",
	/* 角色列表 */
	roleList: [
		[
			{ text: "财务", value: 6 },
			{ text: "补货员", value: 7}
		]
	],
	/* 是否用户用户角色选择弹窗 */
	showRoleStatus: false,
})

/* 角色选择弹窗确定按钮点击事件 */
const handleRoleStatusConfirm = (e) => {
	const item = e.value[0];
	state.roleText = item.text;
	state.params.roleId = item.value;
	state.showRoleStatus = false;
}

/* 保存按钮点击事件 */
const handleSave = () => {
	if (!state.params.roleId) return Toast("请选择角色");
	if (!state.params.userName) return Toast("请输入您的姓名");
	if (!state.params.mobile) return Toast("请输入手机号码");
	if (!state.params.password) return Toast("请输入登录密码");
	request({
		url: ApiUrl.addUser,
		method: "post",
		data: {
			...state.params
		}
	}).then(res => {
		if (res.status == 0) {
			Toast("新增子账号成功", "success");
			/* 重置数据 */
			handleReset();
			uni.navigateBack();
		} else {
			Toast(res.msg, "error");
		}
	})
}

/* 重置数据 */
const handleReset = () => {
	state.params.roleId = null;
	state.params.mobile = null;
	state.params.password = null;
	state.params.userName = "";
	state.roleText = "";
}
</script>

<template>
  <view class="form">
    <view class="form-item" @click="state.showRoleStatus = true">
      <view class="label">角色</view>
      <view class="arrow">
        <span>{{ state.roleText ? state.roleText : "请选择" }}</span>
        <image src="/static/image/form/right_arrow.png" mode="widthFix" />
      </view>
    </view>
    <view class="form-item">
      <span class="label">姓名</span>
      <input v-model.trim="state.params.userName" placeholder="请输入您的姓名"/>
    </view>
    <view class="form-item">
      <span class="label">手机号码</span>
      <input v-model.trim="state.params.mobile" type="number" placeholder="请输入联系电话"/>
    </view>
    <view class="form-item">
      <span class="label">密码</span>
      <input v-model.trim="state.params.password" type="password" placeholder="请输登录密码"/>
    </view>
  </view>
  <button class="btn large primary" @click="handleSave">保存</button>
	<!-- 角色弹窗 -->
	<u-picker
		:show="state.showRoleStatus"
		:columns="state.roleList"
		@cancel="state.showRoleStatus = false"
		@confirm="handleRoleStatusConfirm" />
</template>

<style scoped lang='scss'>
.form {
  margin-top: 26rpx;
  margin-bottom: 80rpx;
}
.btn {
  display: block;
  width: 90%;
  margin: 0 auto!important;
}
</style>